<template>
  <a-spin :spinning="isTableLoading">
    <div class="modal-header">
      <div class="modal-title"> <team-outlined />{{ l('SelectRoles') }}</div>
    </div>
    <div class="modal-body">
      <!-- 搜索框 -->
      <a-input-search
        name="filterText"
        @search="getSearchData"
        :placeholder="l('SearchWithThreeDot')"
        enterButton
        v-model:value="filterText"
      />
      <!-- 数据部分 -->
      <div class="my-md">
        <a-alert :type="'info'" :showIcon="true">
          <template #message>
            <span v-html="l('GridSelectedXItemsTips', selectedRowKeys.length)"></span>
            <a @click="restCheckStatus()" class="ml-md">{{ l('ClearEmpty') }}</a>
            <a-divider type="vertical"></a-divider>
            <a @click="refresh()">{{ l('Refresh') }}</a>
          </template>
        </a-alert>
      </div>
      <a-table
        size="middle"
        :scroll="{ x: tableWidthScroll, y: tableHeightScroll }"
        :rowKey="(record) => record.value"
        :columns="columns"
        :data-source="dataList"
        :pagination="{
          total: totalItems,
          current: pageNumber,
          pageSize: pageSize,
          showTotal: showTotalInfo,
          showQuickJumper: true,
          showSizeChanger: true,
          change: pageNumberChange,
          showSizeChange: pageNumberChange,
          pageSizeOptions: pageSizeOptions,
          size: 'middle',
        }"
        :rowSelection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
          checkAll: checkAll,
        }"
        @change="tableChange"
      >
      </a-table>
    </div>
    <!-- 按钮 -->
    <div class="modal-footer">
      <a-button :disabled="saving" @click="close()" type="button">
        <close-circle-outlined />
        {{ l('Cancel') }}
      </a-button>
      <a-button :loading="saving" :type="'primary'" @click="handleSubmit()">
        <save-outlined />
        {{ l('Save') }}
      </a-button>
    </div>
  </a-spin>
</template>

<script lang="ts">
  import { ModalPagedListingComponentBase } from '/@/shared/component-base';
  import { OrganizationUnitServiceProxy } from '/@/shared/service-proxies';
  import { CloseCircleOutlined, SaveOutlined, TeamOutlined } from '@ant-design/icons-vue';
  import { defineComponent } from 'vue';
  import _ from 'lodash';
  import {
    FindUsersInput,
    OrganizationUnitListDto,
    RolesToOrganizationUnitInput,
  } from '/@/shared/service-proxies/service-proxies';
  import { ColumnType } from 'ant-design-vue/lib/table';
  import { IPagedRequestDto } from '/@/shared/component-base/interfaces';

  export default defineComponent({
    name: 'add-role',
    components: {
      CloseCircleOutlined,
      SaveOutlined,
      TeamOutlined,
    },
    mixins: [ModalPagedListingComponentBase],
    // props:['filteredInfo','sortedInfo','organizationUnitId'],
    props: {
      organizationUnitId: Number,
    },
    data() {
      return {
        // 搜索
        filterText: '',
        _organizationUnitServiceProxy: new OrganizationUnitServiceProxy(),
        // 用户数据
        dataList: [] as OrganizationUnitListDto[],
      };
    },
    methods: {
      //获取列
      getColumns(): ColumnType<OrganizationUnitListDto>[] {
        return [
          {
            title: 'No',
            customRender: ({ index }) => {
              const a = (this.pageNumber - 1) * this.pageSize + (index + 1);
              return a;
            },
            width: 60,
            fixed: 'left',
          },
          {
            title: this.l('Name'),
            dataIndex: 'name',
            align: 'center',
            key: 'name',
          },
        ];
      },
      /**
       * 获取数据
       */
      fetchDataList(request: IPagedRequestDto, finishedCallback?: () => void) {
        let finduserInput: FindUsersInput = new FindUsersInput();
        finduserInput.organizationUnitId = this.organizationUnitId as number;
        finduserInput.maxResultCount = request.maxResultCount;
        finduserInput.skipCount = request.skipCount;
        finduserInput.filterText = this.filterText;
        this._organizationUnitServiceProxy
          .findRoles(finduserInput)
          .finally(() => {
            finishedCallback!();
          })
          .then((res) => {
            this.showPaging(res);
          });
      },
      /**
       * 提交表单
       */
      handleSubmit() {
        const selectCount = this.selectedRowKeys.length;
        if (selectCount <= 0) {
          this.message.warn(this.l('PleaseSelectAtLeastOneItem'));
          return;
        }
        this.saving = true;
        this.isTableLoading = true;
        let input = {
          organizationUnitId: this.organizationUnitId,
          roleIds: _.map(this.selectedRowKeys, (selectedMember) => Number(selectedMember)),
        };
        let rolesOrganization: RolesToOrganizationUnitInput = new RolesToOrganizationUnitInput();
        rolesOrganization.init(input);
        this._organizationUnitServiceProxy
          .addRoles(rolesOrganization)
          .finally(() => {
            this.saving = false;
            this.isTableLoading = false;
          })
          .then(() => {
            this.notify.success(this.l('SavedSuccessfully'));
            this.success(input.roleIds);
          });
      },
    },
  });
</script>

<style scoped lang="less">
  .modal-header {
    .anticon {
      margin-right: 10px;
    }
  }
</style>
